package com.ccsoft.thread.service;

import java.util.concurrent.TimeUnit;

public class No7Interrupter {
    private static Thread getThread(){
        Thread t = new Thread(() -> {
            while(true){
                System.out.println("执行中...");
                Thread self = Thread.currentThread();
                if(self.isInterrupted()){
                    System.out.println("被打断了");
                    break;
                }
                System.out.println("判断被打断之后的逻辑");
            }
        },"t1");
        return t;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = getThread();
        System.out.println(t.getState());
        t.start();
        System.out.println(t.getState());
        t.interrupt();
        TimeUnit.SECONDS.sleep(3);
        System.out.println(t.isInterrupted());
        /* 运行结果如下。说明线程内检测到被打断的信号后可以自主决定是否退出线程
            在主线程中延迟之后再检测线程的打断标记，会被恢复 - 从 true 恢复为 false
        NEW
        RUNNABLE
        执行中...
        被打断了
        false
         */
    }
}
